import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:my_app/builder/zhujie/json_annotation.dart';
import 'package:source_gen/source_gen.dart';

// LibraryBuilder 生成独立的dart文件
Builder testJsonBuilder(BuilderOptions options) =>
    LibraryBuilder(JsonBuilder());

class JsonBuilder extends GeneratorForAnnotation<JsonAnnotation> {
  @override
  generateForAnnotatedElement(
      Element element, ConstantReader annotation, BuildStep buildStep) {
    if (element is! ClassElement) {
      throw InvalidGenerationSource('入参必须是个class', element: element);
    }

    var className = element.name;
    final buffer = StringBuffer();
    buffer.writeln('import \'${element.librarySource.shortName}\';');
    buffer.writeln('extension ${className}JsonExtension on $className {');
    buffer.writeln('   Map<String, dynamic> toJson() {');
    buffer.writeln('    final Map<String, dynamic> data = {};');
    for (var field in element.fields) {
      buffer.writeln('    data[\'${field.name}\'] = ${field.name};');
    }
    buffer.writeln('    return data;');

    buffer.writeln('    }');

    buffer.writeln('static fromJson(Map<String, dynamic> json) {');
    buffer.writeln('  return $className(');
    for (var field in element.fields) {
      buffer.writeln('      json[\'${field.name}\'],');
    }

    buffer.writeln('    );');
    buffer.writeln('}');
    buffer.writeln('    }');

    return buffer.toString();
  }
}
